﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Web;
using System.Net;
using System.Xml.Linq;
using AtomPayloadAnalyzer;
using System.Security.Cryptography.X509Certificates;
using System.Diagnostics;
using System.IO;
using System.Threading;
using ODataTestFrameworkCore.shared;
using ODataFeedDownLoadTool;

namespace ODataRegression.Framework.Core.Shared
{


    class HTTPHelpers
    {
        public static ODataTestResult DownloadAllFeeds(string url)
        {
            string logMessage;
            X509Certificate userCert = null;
            ODataTestResult result = null;

            string httpStatusCode = string.Empty;
            DateTime endTime = DateTime.Now; ;
            DateTime startTime = DateTime.Now;



            userCert = CertificateHalper.GetClientCertificate(TestConfigReader.TestEngineSettings[TestEngineSettingsTypes.UserName]);
            bool traceOnly = Convert.ToBoolean(TestConfigReader.TestEngineSettings[TestEngineSettingsTypes.TraceOnly]);
            string messge = string.Empty;
            httpStatusCode = "SKIPPED";
            if (!traceOnly)
            {

                try
                {
                    string filename = Guid.NewGuid().ToString() + ".txt";
                    ODataReader OReader = new ODataReader(url, userCert);

                    Exception e = OReader.SaveAsText(filename, '|');

                    startTime = OReader.StartTime;
                    endTime = OReader.EndTime;

                    result = new ODataTestResult(startTime, endTime, "OK", e, null);
                    messge = string.Format("Download completed , RowCount={0} ,PageCount={1} LogFileName={2}", OReader.TotalDataRows, OReader.TotalPages, filename);
                }
                catch (Exception e)
                {

                    ConsoleLogger.LogException(e);
                    httpStatusCode = "ERROR";
                    //messge = e.Message + Environment.NewLine + e.StackTrace;
                    result = new ODataTestResult(startTime, endTime, httpStatusCode, e, null);

                }
            }
            else
            {
                httpStatusCode = "SKIPPED";
                result = new ODataTestResult(startTime, endTime, httpStatusCode, null, null);

            }


            // Debug.WriteLine("Finished Executing URL=" + url);
            logMessage = string.Format("Execution Finished on ThreadID={0} Status={1} URL={2}", Thread.CurrentThread.ManagedThreadId, httpStatusCode, url);
            ConsoleLogger.LogMessage(logMessage);
            result.OriginalResponceString = messge;
            //webResp.Close();
            return result;
        }

        public static ODataTestResult ExecuteGet(string url,  bool isTestExecuteRequest = true)
        {
            string logMessage;
            // logMessage = string.Format("Execution Started on ThreadID={0} URL={1}", Thread.CurrentThread.ManagedThreadId, url);
            // ConsoleLogger.LogMessage(logMessage);

            X509Certificate userCert = null;
            ODataTestResult result = null;
            HttpWebResponse webResp = null;

            string httpStatusCode = string.Empty;

            DateTime endTime = DateTime.Now; ;
            DateTime startTime = DateTime.Now;

            HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);

            WebReq.Timeout = Convert.ToInt32(TestConfigReader.TestEngineSettings[TestEngineSettingsTypes.TestTimeOut]);
            WebReq.UseDefaultCredentials = true;
            WebReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0)";
            userCert = CertificateHalper.GetClientCertificate(TestConfigReader.TestEngineSettings[TestEngineSettingsTypes.UserName]);
            if (userCert != null)
            {
                WebReq.ClientCertificates.Add(userCert);
            }
            else
            {
                // If config do not provide certificate name then supply all ther certificate to request 
                foreach (X509Certificate cert in CertificateHalper.GetClientCertificates())
                {
                    WebReq.ClientCertificates.Add(cert);
                }
            }


            bool traceOnly = Convert.ToBoolean(TestConfigReader.TestEngineSettings[TestEngineSettingsTypes.TraceOnly]);

            httpStatusCode = "SKIPPED";
            if (!traceOnly || !isTestExecuteRequest)
            {

                try
                {
                    startTime = DateTime.Now;
                  //  try
                   // {
                        webResp = (HttpWebResponse)WebReq.GetResponse();
                        //endTime = DateTime.Now;
                   // }
                  //  catch (Exception)
                   // {
                        /// Some time request failed in first attempt so putting retry logic
                      //  ConsoleLogger.LogMessage(string.Format("ERROR:GET Request failed for first time retrying URL={0}", url));
                       // webResp = (HttpWebResponse)WebReq.GetResponse();

                       // endTime = DateTime.Now;
                  //  }
                    endTime = DateTime.Now;

                    httpStatusCode = webResp.StatusCode.ToString();
                    result = new ODataTestResult(startTime, endTime, httpStatusCode, null, webResp);


                }
                
                catch (Exception e)
                {
                    endTime = DateTime.Now;
                    ConsoleLogger.LogException(e);
                    httpStatusCode = "ERROR";
                    result = new ODataTestResult(startTime, endTime, httpStatusCode, e, webResp);

                }

            }
            else
            {
                httpStatusCode = "SKIPPED";
                result = new ODataTestResult(startTime, endTime, httpStatusCode, null, null);

            }

            // Debug.WriteLine("Finished Executing URL=" + url);
            logMessage = string.Format("Execution Finished on ThreadID={0} Status={1} URL={2}", Thread.CurrentThread.ManagedThreadId, httpStatusCode, url);
            ConsoleLogger.LogMessage(logMessage);

            //webResp.Close();
            return result;
        }

        public static string ExecuteGet(string url)
        {

            string resp = null;
            //X509Certificate userCert = null;
           // ODataTestResult result = null;
            HttpWebResponse webResp = null;

            HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);

            WebReq.Timeout = 4 * 60 * 1000;
            
            WebReq.UseDefaultCredentials = true;
            WebReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0)";
            
                // If config do not provide certificate name then supply all ther certificate to request 
                foreach (X509Certificate cert in CertificateHalper.GetClientCertificates())
                {
                    WebReq.ClientCertificates.Add(cert);
                }
          

            webResp = (HttpWebResponse)WebReq.GetResponse();
            StreamReader sr = new StreamReader(webResp.GetResponseStream());
             resp = sr.ReadToEnd();
           webResp.Close();

           return resp;
        }

    }
}
